package com.ruoyi.tzzl.config.redis;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.tzzl.domain.WzProgramUser;
import com.ruoyi.tzzl.service.IWzProgramUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.jdbc.core.JdbcTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 首先redis配置文件中需要打开配置：搜索：notify-keyspace-events Ex 找到后，放开注释
 * @author by caoyong
 * @date 2022/12/10
 **/
@Slf4j
public class KeyExpiredListener extends KeyExpirationEventMessageListener {
    @Autowired
    private IWzProgramUserService wzProgramUserService;

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 过期的key
        String key = new String(message.getBody(), StandardCharsets.UTF_8);
        if (key.contains("KTHY")){
            log.info("{},会员到期",key);
          String userId =  key.substring(4);
          WzProgramUser user = wzProgramUserService.getById(userId);
          user.setUserLevel("1");
          user.setRole("1");
          wzProgramUserService.updateById(user);
        } else if (key.contains("ZX")){
            String userId =  key.substring(2);
            WzProgramUser user = wzProgramUserService.getById(userId);
            user.setOnlineStatus("0"); //离线状态
            user.setUpdateTime(new Date());
            wzProgramUserService.updateById(user);
        }

    }
}
